package com.kzd.gtboon.main.game

import android.Manifest
import android.graphics.BitmapFactory
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.kzd.gtboon.R
import com.kzd.gtboon.custom.createViewTextBottom
import com.kzd.gtboon.databinding.IncludeAppRecyclerBinding
import com.kzd.gtboon.entity.*
import com.kzd.gtboon.jetpack.vm.GameViewModel
import com.kzd.gtboon.main.game.adapter.*
import com.kzd.gtboon.main.popup.ServiceCodePopup
import com.kzd.gtboon.main.toGameVipActivity
import com.kzd.gtboon.utils.saveImageToGallery
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel
import java.lang.StringBuilder

class GameDetailsFragment : OwnerViewBindingFragment<IncludeAppRecyclerBinding>() {

    companion object {
        fun newInstance(): GameDetailsFragment {
            return GameDetailsFragment()
        }
    }

    private val mServiceCodePopup: ServiceCodePopup by lazy {
        ServiceCodePopup(context = requireContext()) { _, type ->
            requestDangerousPermissions(arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ), requestCode = type)
        }
    }

    private val mDetailsAdapter = DetailsAdapter1()

    private val mViewModel:GameViewModel by lazy {
        ownerViewModel(requireActivity())
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> IncludeAppRecyclerBinding
        get() = IncludeAppRecyclerBinding::inflate

    override fun initView() {
        mViewBinding.rvAppRecyclerBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mDetailsAdapter

        mDetailsAdapter.setOnItemChildClickListener { _, view, _ ->
            if (view.id == R.id.tvGameDetailsGraphicVip) {
                val title = mViewModel.gameDetailsLiveData.value?.data?.data?.name ?: ""
                val vip = mViewModel.gameDetailsLiveData.value?.data?.data?.vip
                val vipStr = mViewModel.gameDetailsLiveData.value?.data?.data?.vip_str
                val vipJson = GsonUtils.toJson((vip ?: mutableListOf<GameVip>()))
                toGameVipActivity(title, vipJson, vipStr)
            } else if (view.id == R.id.tvGameDetailsNullQQ) {
                val image = mViewModel.userServiceLiveData.value
                    ?.data?.data?.qy_wx_img
                mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                    R.mipmap.ic_40008
                } else image, 1)
                    .showPopupWindow()
            }
        }
    }

    override fun initViewMode() {
        mViewModel.gameDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val gameDetails: GameDetails = response.data?.data
                ?: return@observe
            val details = mutableListOf<GameDetailsItem<*>>()
            if (!gameDetails.fuli_info.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_TEXT, title = "特色", text = gameDetails.fuli_info
                )
                details.add(detailsText)
            }
            if (!gameDetails.fuli_info_str.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_NULL, title = "特色", text = gameDetails.fuli_info_str
                )
                details.add(detailsText)
            }
            val detailsGraphic = GameDetailsItem(
                type = ITEM_DETAILS_GRAPHIC,
                title = StringBuilder().append("《")
                    .append(gameDetails.name).append("》VIP表").toString(),
                text = gameDetails.content,
                list = gameDetails.imgs
            )
            details.add(detailsGraphic)
            mDetailsAdapter.setNewInstance(details)

            if (!details.isNullOrEmpty()) {
                mDetailsAdapter.setFooterView(createViewTextBottom(requireContext()))
            }
        })

        mViewModel.gameGuessLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val gameGuess: MutableList<GameBean> = response.data?.data
                ?: return@observe
            if (gameGuess.isNullOrEmpty())
                return@observe
            val detailsList = GameDetailsItem(
                type = ITEM_DETAILS_GUESS,
                title = "猜你想搜",
                list = gameGuess
            )
            mDetailsAdapter.addData(detailsList)
        })
    }

    override fun handlePermissionResult(requestCode: Int, granted: Boolean): Boolean {
        if (!granted) {
            toast("请到应用设置中开启存储权限！")
            return false
        }
        val bitmap = BitmapFactory.decodeResource(resources,
            if (requestCode == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007)
        val fileName = "${if (requestCode == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007}.png"
        if (saveImageToGallery(requireContext(), bitmap, fileName)) {
            toast("已保存")
        } else {
            toast("保存失败")
        }
        return super.handlePermissionResult(requestCode, granted)
    }

}